package com.ty.web.controller;

import com.google.common.collect.Lists;
import com.ty.model.AjaxResult;
import com.ty.model.ImageInfo;
import com.ty.utils.FileUtil;
import com.ty.web.spring.config.properties.TyProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据REST Controller
 *
 * @Author Tommy
 * @Date 2024/4/22
 */
@RestController
@RequestMapping("/rest/data")
@Slf4j
public class DataRestController {

    @Autowired
    private TyProperties tyProperties;

    /**
     * 获取各摄像头变化的图片列表
     */
    @RequestMapping("/images")
    public AjaxResult imageList(@RequestParam(required = false, defaultValue = "20") Integer count) throws Exception {

        // 读取视频图像目录下的所有JPG文件
        long begin = System.currentTimeMillis();
        List<File> files = FileUtil.listsJPG(tyProperties.getVrootPath() + "Changed");
        log.info("读取所有Changed图片列表，耗时：{}ms.", System.currentTimeMillis() - begin);

        // 将图片列表转ImageInfo列表对象
        List<ImageInfo> imageInfoList = this.buildImageInfos(files);
        log.info("构建图像列表对象，累计耗时：{}ms.", System.currentTimeMillis() - begin);

        // 图片按SN分组，并取TOP20数据
        Map<String, List<ImageInfo>> imageInfoGroup = imageInfoList.stream().sorted(Comparator.comparing(ImageInfo::getLastModified, Comparator.reverseOrder()))
                .collect(Collectors.groupingBy(ImageInfo::getCameraSN));
        for (Map.Entry<String, List<ImageInfo>> entry : imageInfoGroup.entrySet()) {
            List<ImageInfo> values = entry.getValue().stream().limit(count).toList();
            entry.setValue(values);
        }
        log.info("图像文件列表处理总耗时：{}ms.", System.currentTimeMillis() - begin);
        return AjaxResult.success(imageInfoGroup);
    }

    /*
     * 构建ImageInfo列表对象
     */
    List<ImageInfo> buildImageInfos(List<File> files) {
        List<ImageInfo> imageInfoList = Lists.newArrayList();
        if (null != files && !files.isEmpty()) {
            int bindex = files.get(0).getPath().lastIndexOf("Changed") - 1;
            for (File f : files) {
                String path = f.getPath();
                path = path.substring(bindex).replace("\\", "/");

                String name = f.getName();
                String baseName = FilenameUtils.getBaseName(name);
                String[] arr = baseName.split("\\_");
                double similarity = 0;
                if (arr.length > 1) {
                    baseName = arr[0];
                    similarity = Double.parseDouble(arr[1]);
                } else {
                    baseName = arr[0];
                }

                ImageInfo img = new ImageInfo();
                img.setPath(path);
                img.setCameraSN(f.getParentFile().getName());
                img.setName(name);
                img.setLastModified(Long.parseLong(baseName));
                img.setId(img.getCameraSN() + baseName);
                img.setSimilarity(similarity);

                imageInfoList.add(img);
            }
        }
        return imageInfoList;
    }
}
